import {DownloadOutlined, PlusOutlined} from '@ant-design/icons';
import { Button, Divider, message, Input, Popconfirm, Select, TreeSelect} from 'antd';
import React, { useState, useRef, useEffect, useLayoutEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import {transTitle, handleReturnMD5, saveFileAs} from '@/utils/utils';
import FormItem from 'antd/lib/form/FormItem';

import {
  queryRule,
  updateRule,
  addRule,
  removeRule,
  queryDefaultRule,
  queryStore,
  salesList,
  queryCommodityClass,
  exportRefund
} from './service';
import styles from '../../global.less';
import {queryPosition} from "@/pages/StuffManagement/UserManagement/service";
import Access from '@/components/Access/Access';
const { Option } = Select;
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields, actionRef) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields }).then((res)=>{
      hide();
      if (res){
        if (res.data){
          message.success('添加成功');
        }else{
          message.error(res.message);
        }
        actionRef.current.reload();
      }
    });
    return true;
  } catch (error) {
    hide();
    // message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param payload
 */

const handleUpdate = async (payload, actionRef) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule(payload).then((res)=>{
      hide();
      if (res){
        if (res.data){
          message.success('修改成功');
        }else{
          message.error(res.message);
        }
        actionRef.current.reload();
      }
    });

    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (payload, actionRef) => {
  const hide = message.loading('正在删除');

  try {
    await removeRule(payload);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    console.log(error);
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = (props) => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [formValue, setFormValue] = useState({});
  const [storeList, setStoreList] = useState([]);
  const [staffId, setStaffId] = useState();
  const [passWordState, setPassWordState] = useState(false);
  const [count, setCount] = useState();
  const [treeValue, handleTreeValue] = useState();
  const [menuValues, setMenuValues] = useState([]);
  const [ClassArray, setClassArray] = useState([]);
  const actionRef = useRef();
  const formRef = useRef();
  const addFormRef = useRef();
  const [positionValue, setPositionValue] = useState();
  const [positionIdArr, setPositionIdArr] = useState([]);
  const [exportRecords, setExportRecords] = useState(false);
  const TreeOnChangeByPosition = (value) => {
    console.log(value);
    handleTreeValue(value);
  };
  const PositionOnChange = (value) => {
    if (value){
      setPositionValue(value);
    }
  };
  const TreeOnChange = (value, label, extra) => {
    handleTreeValue(label.id);
  };
  const handleGetDefaultType = async (payload) => {
    const res = await queryDefaultRule(payload);
    const { data } = res;
    if (payload === 1) {
      addFormRef.current.setFieldsValue({
        consumeScale: data,
      });
    } else {
      addFormRef.current.setFieldsValue({
        rechargeScale: data,
      });
    }
  };
  const handleGetStoreData = async () => {
    try {
      const response = await queryStore({});
      const { data } = response;
      setStoreList(data);
      return true;
    } catch (error) {
      console.log(error);
      return false;
    }
  };
  // const selectStore = (payload, exact) => {
  //   setStoreObj(exact);
  // };
  const handleSalesList = () => {
    salesList()
      .then((res) => {
        const { code } = res;
        if (code === 0) {
          transTitle(res.data.list);

          setMenuValues(res.data.list);
        } else {
          message.info(res.message);
        }
      })
      .catch((err) => {});
  };
  const handleCommodityCLass = () => {
    queryCommodityClass()
      .then((res) => {
        const {code}=res;
       return code===0?setClassArray(res.data):message.info(res.message)
      })
      .then((err) => {
        console.log(err);
      });
  };
  const handleGetPosition = async () => {
    try {
      const { data } = await queryPosition();
      transTitle(data);
      setPositionIdArr(data);
    } catch (error) {
      return false;
    }
  };
  useEffect(() => {
    handleGetStoreData();
    handleCommodityCLass();
    handleGetPosition();
  }, []);
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '姓名为必填项',
          },
        ],
      },
    },
    {
      title: '工号',
      dataIndex: 'number',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '工号为必填项',
          },
        ],
      },
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      valueType: 'text',
    },
    {
      title: '密码',
      dataIndex: 'password',
      valueType: 'password',
      hideInForm: formValue,
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '密码为必填项',
          },
        ],
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="请输入" type="password" autoComplete="new-password" />;
      },
    },
    {
      title: '充值比例',
      dataIndex: 'rechargeScale',
      valueType: 'text',
      hideInSearch: true,
      render: (payload) => {
        return <div>{payload}% </div>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="请输入" suffix="%" />;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '充值比例为必填项',
          },
        ],
      },
    },
    {
      title: '消费比例',
      dataIndex: 'consumeScale',
      valueType: 'text',
      hideInSearch: true,
      render: (payload) => {
        return <div>{payload}% </div>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="请输入" suffix="%" />;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '消费比例为必填项',
          },
        ],
      },
    },
    {
      title: '提成比例',
      dataIndex: 'commissionScale',
      hideInSearch: true,
      render: (payload) => {
        return <div>{payload}% </div>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="请输入" suffix="%" defaultValue={0} />;
      },
    },
    {
      title: '所属门店',
      dataIndex: 'storeId',
      valueType: 'text',
      render: (_, record) => {
        return <div>{record.storeName} </div>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select
            placeholder="请选择所在店铺"
            allowClear
            showSearch
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {storeList&&storeList.length>0?storeList.map((item_, index) => {
              return (
                <Option value={item_.id} key={item_.id}>
                  {item_.name}
                </Option>
              );
            }):null}
          </Select>
        );
      },
    },
    {
      title: '父级',
      dataIndex: 'parentId',
      hideInSearch: true,
      hideInTable: true,
      render: (_, record) => {
        return <span>{record.parentName}</span>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false}>
            <TreeSelect
              showSearch
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择父级"
              allowClear
              treeDataSimpleMode
              treeData={menuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onSelect={TreeOnChange}
            />
          </FormItem>
        );
      },
    },
    {
      title: '业务类型',
      dataIndex: 'goodsCategoryId',
      valueType: 'text',
      hideInSearch: true,
      hideInTable:true,
      // render: (_, record) => {
      //   return <span>{record.type === 1 ? '普通' : '生活超市'}</span>;
      // },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择类型" allowClear>
            {ClassArray.length>0?ClassArray.map((item_, index) => {
              return (
                <Option value={item_.id} key={item_.id}>
                  {item_.name}
                </Option>
              );
            }):null}
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '类型为必选项',
          },
        ],
      },
    },
    {
      title: '职位',
      dataIndex: 'positionId',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} className="formItem_div">
            <TreeSelect
              showSearch
              value={positionValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择职位"
              allowClear
              treeDataSimpleMode
              treeData={positionIdArr}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={TreeOnChangeByPosition}
            />
          </FormItem>
        );
      },
    },
    {
      title: 'IM TOKEN',
      dataIndex: 'accessToken',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '老模式',
      dataIndex: 'oldFlag',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {

        return (
          <Select placeholder="是否开启老模式出库" allowClear >
            <Option value={true} >
              开启
            </Option>
            <Option value={false} >
              关闭
            </Option>
          </Select>
        );
      },
      render: (dom, entity) => {
        return <a>{formValue.oldFlag ? '开启' : '关闭'}</a>;
      },
    },
    {
      title: '工厂盘点',
      dataIndex: 'stockCheckFlag',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="是否开启工厂盘点" allowClear >
            <Option value={true}>
              开启
            </Option>
            <Option value={false}>
              关闭
            </Option>
          </Select>
        );
      },
      render: (dom, entity) => {
        return <a>{formValue.stockCheckFlag ? '开启' : '关闭'}</a>;
      },
    },
    {
      title: '修改会员',
      dataIndex: 'updateFlag',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="是否开启修改会员" allowClear >
            <Option value={true}>
              开启
            </Option>
            <Option value={false}>
              关闭
            </Option>
          </Select>
        );
      },
      render: (dom, entity) => {
        return <a>{formValue.updateFlag ? '开启' : '关闭'}</a>;
      },
    },
    {
      title: '原料管理',
      dataIndex: 'stuffFlag',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="是否开启原料管理" allowClear >
            <Option value={true}>
              开启
            </Option>
            <Option value={false}>
              关闭
            </Option>
          </Select>
        );
      },
      render: (dom, entity) => {
        return <a>{formValue.stuffFlag ? '开启' : '关闭'}</a>;
      },
    },
    {
      title: '成品入库',
      dataIndex: 'stockInFlag',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="是否开启成品入库" allowClear >
            <Option value={true}>
              开启
            </Option>
            <Option value={false}>
              关闭
            </Option>
          </Select>
        );
      },
      render: (dom, entity) => {
        return <a>{formValue.stockInFlag ? '开启' : '关闭'}</a>;
      },
    },
    // {
    //   title: '终端隐藏',
    //   dataIndex: 'hideBaseMenuFlag',
    //   hideInSearch: true,
    //   hideInTable: true,
    //   renderFormItem: (item, { defaultRender, ...rest }, form) => {
    //     return (
    //       <Select placeholder="是否隐藏终端基本功能" allowClear >
    //         <Option value={true}>
    //           隐藏
    //         </Option>
    //         <Option value={false}>
    //           显示
    //         </Option>
    //       </Select>
    //     );
    //   },
    //   render: (dom, entity) => {
    //     return <a>{formValue.hideBaseMenuFlag ? '开启' : '关闭'}</a>;
    //   },
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Access accessKey={"@updateClerkDetail"}>
            <a
              onClick={async () => {
                const payload = JSON.parse(JSON.stringify(record));
                delete payload.password;
                handleCommodityCLass();
                setFormValue(payload);
                handleEditModalVisible(true);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
          </Access>
          <Access accessKey={"@deleteClerk"}>
            <Popconfirm
              placement="top"
              title="确定要删除吗?"
              onConfirm={() => {
                handleRemove(record.id, actionRef);
              }}
              okText="确定"
              cancelText="取消"
            >
              <a onClick={() => {}}>删除</a>
            </Popconfirm>
            <Divider type="vertical" />
          </Access>
          <Access accessKey={"@updateClerkPass"}>
            <a
              onClick={() => {
                setPassWordState(true);
                setStaffId(record.id);
                // setFormValue(record);
              }}
            >
              修改工号密码
            </a>
          </Access>

        </>
      ),
    },
  ];
  const passColumns = [
    {
      title: '密码',
      dataIndex: 'password',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '密码为必填项',
          },
        ],
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="请输入" type="password" autoComplete="new-password" />;
      },
    },
  ];

  return (
    <div>
      <ProTable
        headerTitle="工号列表"
        actionRef={actionRef}
        formRef={formRef}
        rowKey="id"
        bordered
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Access accessKey={"@newClerkAccount"}>
            <Button
              type="primary"
              onClick={() => {
                setFormValue();
                handleGetDefaultType(1);
                handleGetDefaultType(2);
                handleModalVisible(true);
                handleSalesList();
                queryRule({});
                handleCommodityCLass();
              }}
            >
              <PlusOutlined /> 新建工号
            </Button>
          </Access>
          ,
          <Access accessKey={"@exportClerkAccount"}>
            <Button
              type="primary"
              danger
              loading={exportRecords}
              icon={<DownloadOutlined/>}
              onClick={() => {
                setExportRecords(true);
                exportRefund().then((res) => {
                  if (res) {
                    saveFileAs(res, '工号');
                  }
                  setExportRecords(false);
                });
              }}
            >
              导出工号
            </Button>
          </Access>
         ,
        ]}
        beforeSearchSubmit={(payload) => {
          return payload;
        }}
        request={(params, sorter, filter) => {
          return queryRule({ ...params });
        }}
        postData={(params) => {
          const { list, total } = params;
          setCount(total);
          return list||[];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
        rowSelection={false}
        // options={false}
      />
      <CreateForm
        title="新建工号"
        onCancel={() => {
          handleModalVisible(false);
        }}
        modalVisible={createModalVisible}
        width={800}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            // value.storeId = storeObj.value;
            // value.storeName = storeObj.children;
            value.commissionScale?null:value.commissionScale=0;
            value.password = handleReturnMD5(value.password);
            const success = await handleAdd(value, actionRef);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          formRef={addFormRef}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        title="修改工号"
        onCancel={() => {
          handleEditModalVisible(false);
        }}
        modalVisible={createEditModalVisible}
        width={800}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.id = formValue.id;
            // value.storeId = storeObj.value;
            // value.storeName = storeObj.children;
            value.commissionScale?null:value.commissionScale=0;
            const success = await handleUpdate(value, actionRef);
            if (success) {
              handleEditModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
          form={{
            initialValues: formValue,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
        />
      </CreateForm>
      <CreateForm
        onCancel={() => setPassWordState(false)}
        modalVisible={passWordState}
        title="修改工号密码"
        width={600}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.id = staffId;
            value.password = handleReturnMD5(value.password);
            const success = await handleUpdate(value, actionRef);
            if (success) {
              setPassWordState(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={passColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
        />
      </CreateForm>
    </div>
  );
};

export default TableList;
